<?php
namespace app\admin\controller;

class Featured extends Base{
    private $types;

    public function _initialize() {
        parent::_initialize();
        //获取推荐位类别（extra目录featured.php文件）
        $this->types = config('featured.featured_type');
    }

    public function index(){
        //获取推荐位类别（extra目录featured.php文件）
        $types = config('featured.featured_type');
        $type = input('get.type', 0, 'intval');
        //获取列表数据
        $results = $this->modelObj->getFeaturedsByType($type);
        return $this->fetch('',[
            'types' => $types,
            'type' => $type,
            'results' => $results,
        ]);
    }

    public function add(){
        if(request()->isPost()){
            //入库逻辑
            $data = input('post.');
            //数据校验
            $validate = validate('Featured');//表单验证器
            if(!$validate->check($data)){
                $this->error($validate->getError());
            }
            //数据入库并返回id
            $id = $this->modelObj->add($data);
            if($id){
                $this->success('添加成功');
            } else {
                $this->error('添加失败');
            }

        } else {
            return $this->fetch('',[
                'types' => $this->types,
            ]);
        }
    }

    /**
     * 修改页面
     * @param int $id 修改的目标id
     * @return mixed
     */
    public function edit($id = 0){
        if(intval($id) < 1){
            $this->error('参数不合法！');
        }
        $result = $this->modelObj->get($id);
        return $this->fetch('', [
            'types' => $this->types,
            'result' => $result,
        ]);
    }

    /**
     * 数据更新入库
     */
    public function save(){
        //严格校验是否为POST
        if(!request()->isPost()){
            $this->error('请求失败');
        }
        $data = input('post.'); //获取“添加分类”表单数据
        $validate = validate('Featured');//表单验证器
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }
        if(!empty($data['id'])){
            return $this->update($data);
        }
    }
}